<?php

class UserBusiness {

	public function createUser($user, $address){
		try{

			$salt = md5(date("Y-m-d"));

			$pass = crypt($user['password'],$salt);

			$pass = hash('sha512',$pass);

			$db = Zend_Db_Table::getDefaultAdapter();

			$db->insert('us_client', array(
			'name'     		=> $user['name'],
			'login' 		=> $user['login'],
			'gender' 		=> $user['gender'],
			'cpf' 			=> $user['cpf'],
			'phone' 		=> $user['phone'],
			'celphone' 		=> $user['celphone'],
			'email'    		=> $user['email'],
			'password' 		=> $pass,
			'user_type' 	=> $user['user_type'],
			'birth' 		=> $user['birth'],
			'register_date'	=> date("Y-m-d"),
			'flag_mail'		=> $user['flag_mail'],
			'us_status'		=> 0,
			));

			$idt_client = $db->lastInsertId();

			$db->insert('us_address', array(
			'idt_client'	=> $idt_client,
			'cep'			=> $address['cep'],
			'type'			=> $address['type'],
			'address' 		=> $address['address'],
			'number' 		=> $address['number'],
			'comp' 			=> $address['comp'],
			'neigh' 		=> $address['neigh'],
			'city' 			=> $address['city'],
			'state' 		=> $address['state'],
			'reference' 	=> $address['reference'],
			));

			return $idt_client;

		}catch (Exception $e){
			echo $e;
		}
	}

	public function activeClient($id){
		try {
			$db = Zend_Db_Table::getDefaultAdapter();

			$where = $db->quoteInto ( 'idt_client' . ' = ?', $id );

			$update = $db->update ('us_client', array(
			'us_status'    => 1,
			), $where);

		} catch (Exception $e) {
			Zend_Registry::get('log')->err('activeClient() Erro ao ativar usuário id: '.$id.' ' .$e.'');
		}
	}

	public function updateLastAccess($id){
		try{

			$date = date("Y-m-d");

			$db = Zend_Db_Table::getDefaultAdapter();

			$where = $db->quoteInto ( 'idt_client' . ' = ?', $id );

			$update = $db->update ('us_client', array(
			'dat_last_access'    => $date,
			), $where);

		}catch (Exception $e){
			echo $e;
		}
	}

	public function updatePassword($user, $passwd){
		try{
				
			$salt = md5($user['register_date']);

			$pass = crypt($passwd,$salt);

			$pass = hash('sha512',$pass);

			$db = Zend_Db_Table::getDefaultAdapter();

			$where = $db->quoteInto ( 'idt_client' . ' = ?', $user['idt_client'] );

			$update = $db->update ('us_client', array(
			'password'    => $pass,
			), $where);

		}catch (Exception $e){
			echo $e;
		}
	}


	public function getUserByLogin($login){

		$db = Zend_Db_Table::getDefaultAdapter();
		$select = $db->fetchRow("SELECT * FROM us_client where login = '$login'");

		return $select;
	}

	public function getUserByEmail($email){

		$db = Zend_Db_Table::getDefaultAdapter();
		$select = $db->fetchRow("SELECT * FROM us_client where email = '$email'");

		return $select;
	}

	public function getUserByCpf($cpf){

		$db = Zend_Db_Table::getDefaultAdapter();
		$select = $db->fetchRow("SELECT * FROM us_client where cpf = '$cpf'");

		return $select;
	}

}